using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using LocalBoard.Domain;
using LocalBoard.Controller;
using LocalBoard.Persistence;
using LocalBoard.Web.UserControls;

namespace LocalBoard.Web
{
	/// <summary>
	/// Summary description for manageClub.
	/// </summary>
	public partial class manageClub : ClubPage
	{

		private readonly AdminController _adminController = new AdminController(Global.AccessorFactory);

		protected void Page_Load(object sender, System.EventArgs e)
		{
			if(!ClubController.GetClubSecurity().CanUserManageClub(this.ClubUser))
				Security.RedirectToHome();
			if(!this.IsPostBack)
			{
				clubInformation.ClubId.Text = Club.Id.ToString();
				clubInformation.InitializeClubInformation();
				ReloadBoardList();
				ReloadRoleList();
				ReloadUserList();
			}
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    

		}
		#endregion

		#region Helper
		private void ReloadBoardList()
		{
			boardList.DataSource = ClubController.GetBoardList();
			boardList.DataTextField = "Name";
			boardList.DataValueField = "Id";
			boardList.DataBind();
		}
		private void ReloadRoleList()
		{
			ArrayList allRoleList = GetRoleListFromHashtable(ClubController.GetAllClubRoles());
			roleList.DataSource = allRoleList;
			roleList.DataTextField = "Name";
			roleList.DataValueField = "Id";
			roleList.DataBind();
			roleListForBoard.DataSource = allRoleList;
			roleListForBoard.DataTextField = "Name";
			roleListForBoard.DataValueField = "Id";
			roleListForBoard.DataBind();
			roleListForUser.DataSource = allRoleList;
			roleListForUser.DataTextField = "Name";
			roleListForUser.DataValueField = "Id";
			roleListForUser.DataBind();
		}
		private void ReloadUserList()
		{
			userList.DataSource = GetUserListFromHashtable(ClubController.GetAllUsersInClub());
			userList.DataTextField = "UserId";
			userList.DataValueField = "Id";
			userList.DataBind();
		}

		private ArrayList GetUserListFromHashtable(Hashtable allUserHashTable)
		{
			ArrayList list = new ArrayList();
			foreach(int userId in allUserHashTable.Keys)
			{
				list.Add(_adminController.GetUser(userId));
			}
			return list;
		}

		private ArrayList GetRoleListFromHashtable(Hashtable roles)
		{
			ArrayList roleList = new ArrayList();
			if(roles == null)
				return roleList;
			foreach(int key in roles.Keys)
			{
				roleList.Add(roles[key]);
			}
			return roleList;
		}
		private void SelectBoardInTheList(int boardId)
		{
			boardList.SelectedValue = boardId.ToString();
		}
		private string GetSelectedBoardName()
		{
			return boardList.SelectedItem.Text;
		}

		private Board GetSelectedBoard(string boardId)
		{
			int id = GetIntFromString(boardId);
			if(id == 0)
				return null;
			return ClubController.GetBoard(id);
		}
		
		private void initializeBoardControls(string name, string managerId, int accessRoleId, string accessRoleName, int postRoleId, string postRoleName)
		{
			boardNameTBox.Text = name;
			boardManager.Text = managerId;
			boardAccessRole.Text = accessRoleName;
			boardPostRole.Text = postRoleName;
			boardManagerId.Value = managerId;
			boardAccessRoleId.Value = accessRoleId.ToString();
			boardPostRoleId.Value = postRoleId.ToString();
		}
		private string GetUserRoleName(int roleId)
		{
			UserRole userRole = _adminController.GetUserRole(roleId);
			return userRole != null ? userRole.Name : "";
		}

		private int GetIntFromString(string value)
		{
			if(value == null || value.Length == 0)
				return 0;
			return Convert.ToInt32(value);
		}
		private bool IsRoleIdInListItemList(int roleId, ListItemCollection listItemCollection)
		{
			foreach(ListItem item in listItemCollection)
			{
				if(roleId == Int32.Parse(item.Value))
					return true;
			}
			return false;
		}
		private bool IsRoleIdInRoleList(int roleId, ArrayList roles)
		{
			foreach(UserRole role in roles)
			{
				if(role.Id == roleId)
					return true;
			}
			return false;
		}

		private void ReloadUserRoleList(ArrayList roles)
		{
			if(roles == null)
				return;
			userRoleList.DataSource = roles;
			userRoleList.DataTextField = "Name";
			userRoleList.DataValueField = "Id";
			userRoleList.DataBind();
		}
		#endregion

		#region Event handler
		#region Board related
		protected void BoardList_SelectedIndexChanged(object sender, EventArgs e)
		{
			Board board = GetSelectedBoard(boardList.SelectedValue);
			if(board != null)
			{
				initializeBoardControls(GetSelectedBoardName(),
				                        board.Manager != null ? board.Manager.UserId : "",
				                        board.AccessRoleId, GetUserRoleName(board.AccessRoleId),
				                        board.PostRoleId, GetUserRoleName(board.PostRoleId));
			}
		}

		protected void addBoardBtn_Click(object sender, EventArgs e)
		{
			int newBoardId = ClubController.CreateBoard(new Board("New Board",null,0,0,Club.Id,BoardViewType.List));
			ReloadBoardList();
			SelectBoardInTheList(newBoardId);
			boardNameTBox.Text = GetSelectedBoardName();
		}

		protected void deleteBoard_Click(object sender, System.EventArgs e)
		{
			if(boardList.SelectedValue.Length > 0 && Convert.ToInt32(boardList.SelectedValue) > 0 && boardNameTBox.Text.Length > 0)
			{
				ClubController.DeleteBoard(Convert.ToInt32(boardList.SelectedValue));
				Response.Redirect(Request.RawUrl);
			}
		}

		protected void changeBoard_Click(object sender, EventArgs e)
		{
			if(boardList.SelectedValue.Length > 0 && Convert.ToInt32(boardList.SelectedValue) > 0 && boardNameTBox.Text.Length > 0)
			{
				Board targetBoard = ClubController.GetBoard(Convert.ToInt32(boardList.SelectedValue));
				bool dirty = false;
				if(targetBoard.Name != boardNameTBox.Text)
				{
					targetBoard.Name = boardNameTBox.Text;
					dirty = true;
				}
				if((targetBoard.Manager == null && boardManager.Text != "")
					|| (targetBoard.Manager != null && targetBoard.Manager.UserId != boardManager.Text))
				{
					int managerId = GetIntFromString(boardManagerId.Value);
					if(managerId > 0)
						targetBoard.Manager = new Profile(managerId);
					dirty = true;
				}
				int accessRoleId = GetIntFromString(boardAccessRoleId.Value);
				if(targetBoard.AccessRoleId !=  accessRoleId)
				{
					targetBoard.AccessRoleId = accessRoleId;
					dirty = true;
				}
				int postRoleId = GetIntFromString(boardPostRoleId.Value);
				if(targetBoard.PostRoleId != postRoleId)
				{
					targetBoard.PostRoleId = postRoleId;
					dirty = true;
				}
				if(dirty)
				{
					ClubController.UpdateBoard(targetBoard);
					Response.Redirect(Request.RawUrl);
				}
			}
		}

		protected void addBoardManagerBtn_Click(object sender, EventArgs e)
		{
			if(userList.SelectedIndex < 0)
				return;
			boardManager.Text = userList.SelectedItem.Text;
			boardManagerId.Value = userList.SelectedItem.Value;
		}

		protected void deleteBoardManager_Click(object sender, EventArgs e)
		{
			boardManager.Text = "";
			boardManagerId.Value = "";
		}

		protected void addBoardAccessRoleBtn_Click(object sender, System.EventArgs e)
		{
			if(roleListForBoard.SelectedIndex < 0)
				return;
			boardAccessRole.Text = roleListForBoard.SelectedItem.Text;
			boardAccessRoleId.Value = roleListForBoard.SelectedItem.Value;
		}

		protected void deleteBoardAccessRole_Click(object sender, System.EventArgs e)
		{
			boardAccessRole.Text = "";
			boardAccessRoleId.Value = "";
		}

		protected void addBoardPostRoleBtn_Click(object sender, System.EventArgs e)
		{
			if(roleListForBoard.SelectedIndex < 0)
				return;
			boardPostRole.Text = roleListForBoard.SelectedItem.Text;
			boardPostRoleId.Value = roleListForBoard.SelectedItem.Value;
		}

		protected void deleteBoardPostRole_Click(object sender, System.EventArgs e)
		{
			boardPostRole.Text = "";
			boardPostRoleId.Value = "";
		}
		#endregion

		#region Club role related
		protected void deleteRole_Click(object sender, EventArgs e)
		{
			ClubController.DeleteUserRole(Int32.Parse(roleList.SelectedValue));
			ReloadRoleList();
		}

		protected void addRole_Click(object sender, EventArgs e)
		{
			if(newRole.Text != "")
			{
				ClubController.CreateClubRole(newRole.Text);
				newRole.Text = "";
				ReloadRoleList();
			}
		}
		#endregion

		#region Club user related
		protected void userList_SelectedIndexChanged(object sender, EventArgs e)
		{
			ReloadUserRoleList(ClubController.GetClubRolesAssignedToUser(Int32.Parse(userList.SelectedValue)));
		}

		protected void addRoleToUser_Click(object sender, EventArgs e)
		{
			ListItem item = new ListItem(roleListForUser.SelectedItem.Text, roleListForUser.SelectedItem.Value);
			userRoleList.Items.Add(item);
		}

		protected void deleteRoleFromUser_Click(object sender, EventArgs e)
		{
			userRoleList.Items.Remove(userRoleList.SelectedItem);
		}

		protected void updateUser_Click(object sender, System.EventArgs e)
		{
			ArrayList currentUserRoleList = ClubController.GetClubRolesAssignedToUser(Int32.Parse(userList.SelectedValue));
			foreach(ListItem item in userRoleList.Items)
			{
				if(!IsRoleIdInRoleList(Int32.Parse(item.Value), currentUserRoleList))
				{
					ClubController.AssignClubRoleToUser(Int32.Parse(item.Value), Int32.Parse(userList.SelectedValue));
				}
			}
			foreach(UserRole role in currentUserRoleList)
			{
				if(!IsRoleIdInListItemList(role.Id, userRoleList.Items))
				{
					ClubController.UnAssignClubRoleFromUser(role.Id, Int32.Parse(userList.SelectedValue));
				}
			}
		}
		#endregion
		#endregion
	}
}
